package com.samshow.core.listener;

import com.samshow.base.constant.Constant;
import com.samshow.base.util.BaseUtil;
import com.samshow.core.cache.ScreenCache;
import com.samshow.res.entity.ScreenEntity;
import com.samshow.res.repository.ScreenRepository;
import onbon.bx05.Bx5GException;
import onbon.bx05.Bx5GScreen;
import onbon.bx05.Bx5GServerListener;
import onbon.bx05.message.file.ControllerConfigFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by niwb on 2017/2/21.
 */
@Component
public class ScreenListener implements Bx5GServerListener {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ScreenRepository screenRepository;



    @Override
    public void connected(String socketId, String netId, Bx5GScreen bx5GScreen) {
        try {
            ControllerConfigFile configFile = bx5GScreen.readConfig();
            int width = configFile.getScreenWidth();
            int height = configFile.getScreenHeight();
            int color = configFile.getColor();
            int oe = configFile.getOePol();
            int data = configFile.getDaPol();
            String name = configFile.getControllerName();

            ScreenEntity screenEntity = new ScreenEntity();
            screenEntity.setId(netId);
            screenEntity.setHeight(height);
            screenEntity.setWidth(width);
            screenEntity.setColor(color);
            screenEntity.setOe(oe);
            screenEntity.setData(data);
            screenEntity.setName(name);
            screenEntity.setConnect(BaseUtil.getCurrentTimestamp());
            screenEntity.setDisconnect(null);
            screenEntity.setStatus(Constant.Screen.STATUS_ON);
            screenRepository.save(screenEntity);
            ScreenCache.INSTANCE.addScreen(netId,bx5GScreen);
        } catch (Bx5GException e) {
            log.error("ScreenListener connected ERROR", e);
        }
    }

    @Override
    public void disconnected(String socketId, String netId, Bx5GScreen bx5GScreen) {
        ScreenEntity screenEntity = screenRepository.findById(netId);
        if (screenEntity == null) {
            log.debug("ScreenListener disconnected screenEntity is NULL");
        }else {
            screenEntity.setDisconnect(BaseUtil.getCurrentTimestamp());
            screenEntity.setStatus(Constant.Screen.STATUS_OFF);
            screenRepository.save(screenEntity);
            ScreenCache.INSTANCE.removeScreen(netId);
        }
    }
}
